﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WorkflowCore.Service.Dto.Fundamentals
{
    /// <summary>
    /// Enum类扩展方法.
    /// </summary>
    public static class EnumExtensions
    {
        /// <summary>
        /// 获取枚举的描述信息
        /// </summary>
        public static string GetDescription(this Enum em)
        {
            Type type = em.GetType();
            FieldInfo fd = type.GetField(em.ToString());
            if (fd == null)
                return string.Empty;
            object[] attrs = fd.GetCustomAttributes(typeof(DescriptionAttribute), false);
            string name = string.Empty;
            foreach (DescriptionAttribute attr in attrs)
            {
                name = attr.Description;
            }
            return name;
        }

        /// <summary>
        /// 获得枚举的DisplayName
        /// </summary>
        /// <param name="eum"></param>
        /// <returns></returns>
        public static string GetDisplayName(this Enum eum)
        {
            //先获取这个枚举的类型
            var type = eum.GetType();
            //通过这个类型获取到值
            var field = type.GetField(eum.ToString());
            var obj = (DisplayAttribute)field.GetCustomAttribute(typeof(DisplayAttribute));
            return obj.Name ?? "";
        }

        /// <summary>
        /// 获得枚举的Name
        /// </summary>
        /// <param name="value">值</param>
        /// <returns></returns>
        public static string GetName<T>(object value)
        {
            return Enum.Parse(typeof(T), value.ToString()).ToString();
        }

        /// <summary>
        /// 获得枚举值
        /// </summary>
        /// <param name="eum"></param>
        /// <returns></returns>
        public static int GetValue(this Enum eum)
        {
            return (int)Enum.Parse(eum.GetType(), eum.ToString());
        }
    }
}
